﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.Configuration;
using com.tiyma.common;
using com.tiyma.httpmoudle;

namespace com.tiyma.components
{
    public static class UserLoginHelper
    {
        /// 给用户注入Ticket，当用户登录的时候调用
        /// </summary>
        public static void SetUserTicket(string userID, string token)
        {
            //获取Cookie的过期时间
            FormsAuthenticationConfiguration formsAuthConfig = new FormsAuthenticationConfiguration();
            int timeOut = Convert.ToInt32(formsAuthConfig.Timeout.TotalMinutes);

            if (timeOut < 1440)
                timeOut = 1440;


            //实例化一个Ticket
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
                userID, DateTime.Now, DateTime.Now.AddMinutes((double)timeOut), false, token);

            //加密Ticket
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);

            //植入Cookie
            HttpCookie ticketCookie = new HttpCookie(FormsAuthentication.FormsCookieName);

            //域名
            if (!string.IsNullOrEmpty(AppConfig.Domain))
                ticketCookie.Domain = AppConfig.Domain;

            ticketCookie.Value = encryptedTicket;

            ticketCookie.Path = "/";

            //  ticketCookie.Expires = DateTime.Now.AddMilliseconds( formsAuthConfig.Timeout.TotalMinutes );
            HttpContext.Current.Response.Cookies.Add(ticketCookie);

            //HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl(userID, false));
        }

        /// <summary>
        /// 更新用户Token
        /// </summary>
        /// <param name="newToken"></param>
        public static void RenewUserTicket(UserToken newToken)
        {
            if (newToken == null | newToken.UserId <= 0)
                return;

            SetUserTicket(newToken.UserId.ToString(), newToken.ToString());
        }

        /// <summary>
        /// 删除用户的Ticket,当用户注销的时候调用
        /// </summary>
        public static void DeleteUserTicket()
        {
            HttpContext.Current.Items.Remove(AuthenticateModule.CONTEXT_ROLE_KEY);
            FormsAuthentication.SignOut();

            HttpCookie ticketCookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];
            if (!string.IsNullOrEmpty(AppConfig.Domain))
                ticketCookie.Domain = AppConfig.Domain;
            ticketCookie.Path = "/";
            ticketCookie.Expires = DateTime.Now.AddDays(-365);
            HttpContext.Current.Response.Cookies.Add(ticketCookie);

            //用户登出
            CookieManager.SetUserLoginOut();
        }
    }
}
